#include "stdafx.h"
#include "Player.h"
void Player::OnMessage(Message *message) {

}

void Player::onMediaData(IMediaData* mediaData) {

	if (mediaData->isVideoData()){

		mVideoList->pack_push((char *)mediaData);
	}
	if (mediaData->isAudioData()){
	
		audioRender->mAudioList->pack_push((char *)mediaData);
	}
	if (mediaData->isAmfData()){
	
		mVideoList->pack_push((char *)mediaData);
	}
}

char* Player::WcharToChar(const wchar_t* wp)
{
	char *m_char;
	int len = WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), NULL, 0, NULL, NULL);
	m_char = new char[len + 1];
	WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), m_char, len, NULL, NULL);
	m_char[len] = '\0';
	return m_char;
}

int Player::getIPFromUI(CString fullUrl, char* IP){

	CString tmpstr1 = fullUrl.Mid(6);
	int tmpint1 = tmpstr1.Find(':');
	CString tmpstr2 = tmpstr1.Left(tmpint1);

	strcpy(IP,  WcharToChar(tmpstr2.GetBuffer()));
	return 1; 
}

int Player::getPortFromUI(CString fullUrl, int* port){

	int tmpint1 = fullUrl.Find(':');
	CString tmpstr1 = fullUrl.Mid(tmpint1+1);

	int tmpint2 = tmpstr1.Find(':');
	CString tmpstr2 = tmpstr1.Mid(tmpint2 + 1);

	int tmpint3 = tmpstr2.Find('/');
	CString tmpstr3 = tmpstr2.Left(tmpint3);

	*port = _ttoi(tmpstr3);
	return 1;
}

int Player::getUrlFromUI(CString fullUrl, char* url){

	int tmpint1 = fullUrl.Find('=');
	CString tmpstr1 = fullUrl.Mid(tmpint1 + 1);

	int tmpint2 = tmpstr1.Find('/');
	CString tmpstr2 = tmpstr1.Left(tmpint2 + 1);
	CString tmpstr3 = tmpstr1.Mid(tmpint2);

	CString tmpstr4;
	tmpstr4 = "live";
	CString tmpstr5 = tmpstr2 + tmpstr4 + tmpstr3;

	strcpy(url, WcharToChar(tmpstr5.GetBuffer()));

	return 1;
}

int Player::setDataSource(CString fullUrl){


	//char strUrl[200] = "rtu.test.tv/live/livestream_1";
	//char strIP[16] = "192.168.199.155";
	//int  intPort = 18899;

	if (!getIPFromUI(fullUrl, strIP)){
	
		return 0;
	}
	if (!getPortFromUI(fullUrl, &intPort)){

		return 0;
	}
	if (!getUrlFromUI(fullUrl, strUrl)){

		return 0;
	}

	mediaSource->prepare(strUrl, strIP, intPort);

	return 1;
}

int Player::prepare(CPlayList* VideoList){

	mVideoList = VideoList;
	return 0;
}

void Player::play(){

	audioRender->start();

	mediaSource->start();

	mediaSource->setMediaCallBack(this);

}

void Player::stop(){

	mediaSource->stop();

	audioRender->stop();

}

void Player::release(){
}

